﻿using System.Text.RegularExpressions;
using TCommon;

namespace TCommunication.Common;

public static class VisaHelper
{
    /// <summary>
    /// 将类似于Com1的串口号转换为visa资源名
    /// </summary>
    /// <param name="portName"></param>
    /// <returns></returns>
    public static OperateResult<string> SerialPortNameConvertToVisaResourceName(string portName)
    {
        
        if (!IsComPortName(portName))
        {
            return OperateResult.CreateFailedResult<string>("不符合串口名规则");
        }

        // 使用正则表达式提取数字部分
        Match match = Regex.Match(portName, @"\d+");
        if (match.Success)
        {
            string portNumber = match.Value;
            var visaResourceName = $"ASRL{portNumber}::INSTR";
            return OperateResult.CreateSuccessResult<string>(visaResourceName);
        }

        return OperateResult.CreateFailedResult<string>("转换失败");
    }
    /// <summary>
    /// 将Visa串口的资源名转换为串口名
    /// </summary>
    /// <param name="resourceName"></param>
    /// <returns></returns>
    public static OperateResult<string> ResourceNameConverterToSerialPortName(string resourceName)
    {
        if (!IsSerialVisaResourceName(resourceName))
        {
            return OperateResult.CreateFailedResult<string>("不符合串口资源名规则");
        }

        //使用正则表达式提取数字部分
        var match = Regex.Match(resourceName,@"\d+");
        if (match.Success)
        {
            var portNumber = match.Value;
            portNumber = $"COM{portNumber}";
            return OperateResult.CreateSuccessResult<string>(portNumber);
        }

        return OperateResult.CreateFailedResult<string>("转换失败");
    }
    /// <summary>
    /// 判断字符串是否为Com串口号
    /// </summary>
    /// <param name="portName"></param>
    /// <returns></returns>
    public static bool IsComPortName(string portName)
    {
        string pattern = @"^COM\d+$"; // 匹配以 "COM" 开头，后跟一个或多个数字的字符串
        Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); // 忽略大小写
        return regex.IsMatch(portName);
    }
    /// <summary>
    /// 判断字符串是否符合串口资源名
    /// </summary>
    /// <param name="resourceName">资源名</param>
    /// <returns></returns>
    public static bool IsSerialVisaResourceName(string resourceName)
    {
        string pattern = @"^ASRL\d+::INSTR$";
        var regex = new Regex(pattern, RegexOptions.IgnoreCase);
        return regex.IsMatch(resourceName);
    }
}